package project.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Users.Client;
import schronisko.*;
import utils.*;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	String type = "activation";
	HttpSession s;
	/**
	 * @see HttpServlet#HttpServlet()
	 */

	String username,password,confirm_password,email;
	static Client c;
	static int ID;
	Queries q = new Queries();

	public Register() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String token = request.getParameter("token");
		out.println("<link rel='stylesheet' type='text/css' href='styles/register.css'>");
		int rows = q.ActivateClient(token, type);
		response.setContentType("text/html");
		out.println("<div class='content'>");
		if(rows == 0){
			out.println("Konto zostalo aktywowane.<br>"
					+ "Mozesz sie zalogowac<br>"
					+ "<a href =index.jsp>Powrot do strony glownej</a>");
			response.setHeader("Refresh", "3; URL=index.jsp");
		}
		else if(rows == -1) {
			out.println("Token wygasl.<br>"
					+ "Zarejestruj sie ponownie <a href=Register.jsp>tutaj</a>");
			response.setHeader("Refresh", "3; URL=Register.jsp");
		}
		out.println("</div>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		s = request.getSession();
		
		c = new Client(0, "", "", "", "", "", "", "", "", "", "");
		//int ID = 0;
		response.setContentType("text/html");
		out.println("<link rel='stylesheet' type='text/css' href='styles/register.css'>");
		username = (String) request.getParameter("username");
		password = (String) request.getParameter("password");
		confirm_password = (String) request.getParameter("confirm_password");
		email = (String) request.getParameter("email");
		String captcha = (String)s.getAttribute("captcha");
		String captcha_typed = request.getParameter("code");
		String name = (String) request.getParameter("name");
		String surname = (String) request.getParameter("surname");
		String city = (String) request.getParameter("city");
		String house = (String) request.getParameter("house");
		String post = (String) request.getParameter("post");
		String pesel = (String) request.getParameter("pesel");
		String id_card = (String) request.getParameter("id_card");
		s = request.getSession();
		out.println("<div class='content'>");
		if(request.getParameter("password") != null){
			if(q.checkUser(username) == 0){ // uzyytkownika nie ma w bazie
				if(password.equals(confirm_password))
				{	
					if(username != "" && password != "" && confirm_password != "" && email != ""){
						if(email.contains("@")){ // adres email jest poprawny
							if(captcha.equals(captcha_typed)){
								ID = q.getNextID();
								q.InsertLoginData(ID,username,password,email);
								c.setID(ID);
								c.setUsername(surname);
								c.setPass(password);
								c.setEmail(email);
								q.InsertClient(c);
								String token = Email_Activation.GenerateToken();

								Email_Activation.SendActivationMail(email,username,token,request.getRequestURL().toString());

								q.InsertToken(token, ID, type);
								out.println("Rejestracje przebiegla pomyslnie.<br>"
										+ "Sprawdz skrzynke pocztowa w celu aktywowania konta<br>"
										+ "<a href=Register_2.jsp>Uzupelnij swoje dane</a>");
								response.setHeader("Refresh", "3; URL=Register_2.jsp");
							}
							else {
								s.setAttribute("register_step", 1); // kod niepoprawny
							}
						}
						else {
							s.setAttribute("register_step", 2); // email niepoprawny
						}
					}
					else {
						s.setAttribute("register_step", 3); // nie podano wszystkich danych
					}
				}
				else {
					s.setAttribute("register_step", 4); // hasla nie takie same
				}
			}
			else {
				s.setAttribute("register_step", 5); // uzytkownik istnieje
			}
			response.sendRedirect("Register.jsp");
		}
		if(request.getParameter("name") != null) {
			if(pesel.length() == 11) {
				if(id_card.length() == 9) {
					c.setID(ID);
					c.setCity(city);
					c.setHouse(house);
					c.setPost(post);
					c.setName(name);
					c.setSurname(surname);
					c.setPESEL(pesel);
					c.setID_card(id_card);
					int success = q.updateClient(c);
					if(success == 0) {
						out.println("Profil zostal zaktualizowany<br> Za 3 sekundy nastapi przeniesienie do strony glownej. <br>"
								+ "Kliknij ponizej, jesli nie nastapi:<br>"
								+ "<a href=index.jsp>Wroc do storny glownej</a>");
						response.setHeader("Refresh","3; URL=index.jsp");
					}
					else s.setAttribute("register_step", 1); // niezidentyfikowany blad
				}
				else {
					s.setAttribute("register_step", 2); // zly numer dowodu
				}
			}
			else {
				s.setAttribute("register_step", 3); // zly pesel
			}
			response.sendRedirect("Register_2.jsp");
		}
		out.println("</div>");
	}
	public void destroy() {
		MySQLConnection.Close();
	}
}
